package org.hao.samples.dao;

import java.util.ArrayList;
import java.util.List;

import org.hao.samples.model.ExamTestVO;
import org.hao.samples.model.Exam_test;
import org.hao.samples.model.PagerModel;
import org.hao.samples.util.SystemContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ExamTestHibernateDAO extends BaseHibernateDAO<Exam_test> implements IExam_testDAO {

	@Override
	public List<Exam_test> findAllExam_test() {
		String hql = "FROM Exam_test";
		return this.find(hql);
	}

	@Override
	public void createExam_test(Exam_test exam_test) throws Exception {
		this.save(exam_test);
	}

	@Override
	public Exam_test getExam_testById(Integer id) {
		Exam_test exam = this.get(id);
		return exam;
	}

	@Override
	public void editExam_test(Exam_test exam_test) throws Exception {
		this.update(exam_test);
	}

	@Override
	public void delete(Integer id) throws Exception {
		Exam_test exam = (Exam_test) this.get(id);
		if (exam != null) {
			this.delete(exam);
		}
	}

	@Override
	public List<Exam_test> findExamTest_ExamTestType() {
		String hql = "FROM Exam_test";
		return this.find(hql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PagerModel<ExamTestVO> findAllByPage() {
		PagerModel<ExamTestVO> page = new PagerModel<ExamTestVO>();
		ArrayList<ExamTestVO> dates = new ArrayList<ExamTestVO>();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getSize();
		// 使用hibernate完成分页
		List<Exam_test> tempDates = this.getSession().createQuery("FROM Exam_test").setFirstResult(offset)
				.setMaxResults(pageSize).list();
		for (Exam_test examtests : tempDates) {
			ExamTestVO examTestVO = new ExamTestVO();
			BeanUtils.copyProperties(examtests, examTestVO);
			examTestVO.setSubId(examtests.getSubject().getSub_id());
			examTestVO.setSubName(examtests.getSubject().getName());
			
			examTestVO.setTestTypeId(examtests.getExamTestType().getId());
			examTestVO.setTestType(examtests.getExamTestType().getTestType());
			examTestVO.setTestTypeScore(examtests.getExamTestType().getTestTypeScore());
			dates.add(examTestVO);
		}
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		// 获取总记录数
		long totalSize = (long) this.getSession().createQuery("select  count(*)  from  Exam_test ").uniqueResult();
		page.setTotalSize(totalSize);
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Exam_test> findExamTestBySubIdTypeId(Integer subId,Integer typeId) {
		String hql = "FROM Exam_test as et where et.examTestType.id =:typeId and et.subject.sub_id =:subId";
		return this.getSession().createQuery(hql).setInteger("typeId", typeId).setInteger("subId", subId).list();
	}
}
